<!-- 事项管理 -->
<template>
  <div class="management-tree">
    <div class="tree-form">
      <div class="tree-box">
        <el-tree :data="data" :props="defaultProps" node-key="primaryKey" default-expand-all>
          <span class="custom-tree-node" slot-scope="{ data }">
            <el-tooltip class="item" effect="dark" :content="data.chargeItemName" placement="bottom">
              <span class="one-line-ellipsis padding-top-5" style="width:53%;display:inline-block;">{{ data.sortCodePath }}{{ data.chargeItemName }}</span>
            </el-tooltip>
            <span class="f-right" style="display:inline-block;">
              <el-button type="text" size="mini" @click.stop="() => moveNode(data)">移动</el-button>
              <el-button type="text" size="mini" @click.stop="() => remove(data)">删除</el-button>
              <el-button type="text" size="mini" @click.stop="() => append(data)" v-if="data.category != 3">添加</el-button>
              <el-button type="text" size="mini" @click.stop="() => update(data)">编辑</el-button>
            </span>
          </span>
        </el-tree>
      </div>
      <div class="form-box" v-if="showChild">
        <div class="form-box-item">
          <el-form :model="typeForm" ref="childForm" label-width="130px" size="small" label-position="right">
            <el-col :span="24">
              <el-form-item label="事项名称" prop="chargeItemName" :rules="{ required: true, message: '事项名称不能为空', trigger: ['blur'] }">
                <el-input v-model="typeForm.chargeItemName"> </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="事项编码" prop="sortCode">
                <el-input type="number" v-model="typeForm.sortCode"> </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24" style="display: none">
              <el-form-item label="事项编码" prop="chargeItemCode">
                <el-input type="number" v-model="typeForm.chargeItemCode" disabled> </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24" style="height: 50px">
              <el-form-item label="类型分类" prop="category" :rules="{ required: true, message: '类型分类不能为空', trigger: 'blur' }">
                <el-select v-model="typeForm.category" placeholder="请选择" :disabled="typeForm.primaryKey ? true : false">
                  <el-option v-for="item in chargeItemCategory" :key="item.key" :label="item.value" :value="item.key"> </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <div v-if="typeForm.category == 2">
              <el-col :span="24">
                <el-form-item label="事项类型" prop="bizType" :rules="{ required: true, message: '事项类型不能为空', trigger: 'blur' }">
                  <el-select v-model="typeForm.bizType" placeholder="请选择" :disabled="typeForm.primaryKey ? true : false">
                    <el-option v-for="item in constantList.chargeItemBizType" :key="item.key" :label="item.value" :value="item.key"> </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <!-- <el-col :span="24">
                  <el-form-item label="事项子类型" prop="chargeItemGroup" :rules="{required: true, message: '事项子类型不能为空', trigger: 'blur'}">
                    <el-select v-model="typeForm.chargeItemGroup" placeholder="请选择"  :disabled="typeForm.primaryKey?true:false">
                      <el-option
                        v-for="item in chiledEventTypeList"
                        :key="item.key"
                        :label="item.value"
                        :value="item.key">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col> -->
              <!-- <el-col :span="24">
                  <el-form-item label="事项类别" prop="matterType" :rules="{required: true, message: '事项类别不能为空', trigger: 'blur'}">
                    <el-select v-model="typeForm.matterType" placeholder="请选择"  :disabled="typeForm.primaryKey?true:false">
                      <el-option
                        v-for="item in constantList.chargeItemMatterType"
                        :key="item.key"
                        :label="item.value"
                        :value="item.key">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col> -->
              <!-- <el-col :span="24">
                  <el-form-item label="填报类型" prop="reportType" :rules="{required: true, message: '填报类型不能为空', trigger: 'blur'}">
                    <el-select v-model="typeForm.reportType" placeholder="请选择"  :disabled="typeForm.primaryKey?true:false">
                      <el-option
                        v-for="item in constantList.chargeItemReportType"
                        :key="item.key"
                        :label="item.value"
                        :value="item.key">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col> -->
              <el-col :span="24">
                <el-form-item label="是否关联资产" prop="relationAssetStatus" :rules="{ required: true, message: '关联资产不能为空', trigger: 'blur' }">
                  <el-select v-model="typeForm.relationAssetStatus" placeholder="请选择">
                    <el-option v-for="item in optionsAssets" :key="item.value" :label="item.label" :value="item.value"> </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24" v-if="typeForm.relationAssetStatus == 1">
                <el-form-item label="关联资产类型" prop="relationAssetTypeList" :rules="{ required: true, message: '关联资产类型不能为空', trigger: 'blur' }">
                  <el-select multiple collapse-tags v-model="typeForm.relationAssetTypeList" placeholder="请选择">
                    <el-option v-for="item in constantList.spaceAssetType" :key="item.key" :label="item.value" :value="item.key"> </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <!-- <el-col :span="24">
                  <el-form-item label="关联事项模版" prop="chargeItemType" :rules="{required: true, message: '关联事项模版不能为空', trigger: 'blur'}">
                    <el-select v-model="typeForm.chargeItemType" placeholder="请选择">
                      <el-option
                        v-for="item in constantList.chargeItemType"
                        :key="item.key"
                        :label="item.value"
                        :value="item.key">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col> -->
            </div>
            <div v-if="typeForm.category == 3">
              <el-col :span="24">
                <el-form-item label="账单类型" prop="billTypeList">
                  <el-select multiple collapse-tags v-model="typeForm.billTypeList" placeholder="请选择" clearable>
                    <el-option v-for="item in constantList.chargeItemBillType" :key="item.key" :label="item.value" :value="item.key"> </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </div>
            <el-col :span="24">
              <el-form-item label="说明" prop="chargeItemDesc">
                <el-input v-model="typeForm.chargeItemDesc"> </el-input>
              </el-form-item>
            </el-col>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button size="mini" @click="cancel">取 消</el-button>
            <el-button size="mini" type="primary" @click="save('childForm')">保存</el-button>
          </span>
        </div>
      </div>
      <el-dialog title="移动节点" z-index="1000" :visible.sync="dialogShow" width="500px" :close-on-click-modal="false" :close-on-press-escape="false">
        <div class="margin-top-10" v-for="item in moveTargetList" :key="item.primaryKey">
          <el-radio v-model="moveTargetKey" :label="item.primaryKey">{{ item.chargeItemName }}</el-radio>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button size="mini" @click="dialogShow = false">取 消</el-button>
          <el-button size="mini" type="primary" @click="confirmMoveNode">确 认</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
  import { askDialog } from '@/pages/limit/assets/util';
  import { requestTips } from '@/common/js/utils';
  import { businessConstant, businessTree, businessCreate, businessUpdate, businessDelete, businessDetail, apiChargeItemList, apiChargeItemMove } from '../../api/masterDataManagement';
  export default {
    data() {
      return {
        defaultProps: {
          children: 'child',
          label: 'chargeItemName',
        },
        data: [],
        showChild: false,
        dialogShow: false,
        moveTargetKey: '',
        moveTargetList: [],
        typeForm: {
          chargeItemName: '',
          sortCode: '',
          chargeItemCode: '',
          bizType: '',
          chargeItemGroup: '',
          chargeItemDesc: '',
          reportType: '',
          matterType: '',
          relationAssetStatus: '',
          relationAssetType: '',
          relationAssetTypeList: [],
          chargeItemType: '',
          primaryKey: '',
          category: '',
          billType: '',
          billTypeList: [],
        },
        constantList: {},
        chargeItemCategory: [],
        chiledEventTypeList: [],
        optionsAssets: [
          { value: 1, label: '是' },
          { value: 0, label: '否' },
        ],
        currentNode: {},
      };
    },
    watch: {
      'typeForm.bizType': {
        immediate: true,
        deep: true,
        handler(val) {
          if (val) this.changeEventType();
        },
      },
    },
    created() {
      this.getBusinessConstant();
      this.getTree();
    },

    methods: {
      checkForm(data) {
        if (this.typeForm.primaryKey && this.typeForm[data] == 0) {
          return true;
        } else if (this.typeForm.primaryKey && this.typeForm[data]) {
          return true;
        } else {
          return false;
        }
      },
      async getBusinessConstant() {
        let res = await businessConstant();
        this.constantList = res;
        this.chargeItemCategory = res.chargeItemCategory;
      },
      changeEventType() {
        switch (this.typeForm.bizType) {
          case '1':
            this.chiledEventTypeList = this.constantList.chargeItemOperationIncomeGroup;
            break;
          case '2':
            this.chiledEventTypeList = this.constantList.chargeItemOperationSpendingGroup;
            break;
          case '3':
            this.chiledEventTypeList = this.constantList.chargeItemNonOperationIncomeGroup;
            break;
          case '4':
            this.chiledEventTypeList = this.constantList.chargeItemNonOperationSpendingGroup;
            break;
          default:
            this.chiledEventTypeList = this.constantList.chargeItemType;
            break;
        }
      },
      async getTree() {
        let res = await businessTree({});
        this.data = res.rows && res.rows.length > 0 ? res.rows[0].child : [];
      },
      randomString(num) {
        num = num || 18;
        var t = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678',
          a = t.length,
          n = '';
        for (let i = 0; i < num; i++) {
          n += t.charAt(Math.floor(Math.random() * a));
        }
        this.typeForm.chargeItemCode = n;
      },
      async addFn() {
        this.showChild = true;
        this.chargeItemCategory = this.constantList.chargeItemCategory;
        Object.keys(this.typeForm).forEach(key => {
          (this.typeForm[key] = null),
            setTimeout(() => {
              this.$refs.childForm.clearValidate(key);
            }, 0);
        });
        this.randomString();
      },
      save(formName) {
        this.$refs[formName].validate(async valid => {
          if (valid) {
            this.typeForm.billType = this.typeForm.billTypeList && this.typeForm.billTypeList.length > 0 ? this.typeForm.billTypeList.join() : '';
            this.typeForm.relationAssetType = this.typeForm.relationAssetTypeList && this.typeForm.relationAssetTypeList.length > 0 ? this.typeForm.relationAssetTypeList.join() : '';
            let res = this.typeForm.primaryKey ? await businessUpdate(this.typeForm) : await businessCreate(this.typeForm);
            this.getTree();
            this.$message.success('添加成功！');
            this.cancel();
          }
        });
      },
      async remove(data) {
        askDialog('确认删除？', async () => {
          if (data.primaryKey) {
            let res = await businessDelete({
              primaryKey: data.primaryKey,
            });
            this.getTree();
            this.$message.success('删除成功！');
          }
        });
        this.cancel();
      },
      async moveNode(data) {
        this.currentNode = data;
        this.moveTargetKey = ""
        let res = await apiChargeItemList({ category: 1 });
        this.moveTargetList = res.rows || [];
        this.dialogShow = true;
      },
      async confirmMoveNode() {
        if (this.currentNode.primaryKey == this.moveTargetKey) {
          this.$message.warning("分类不能做自己的子集!")
          return
        }
        let res = await apiChargeItemMove({ childKey: this.currentNode.primaryKey, parentKey: this.moveTargetKey });
        requestTips(res, () => {
          this.dialogShow = false;
          this.getTree();
        });
      },
      append(data) {
        Object.keys(this.typeForm).forEach(key => {
          (this.typeForm[key] = null),
            setTimeout(() => {
              this.$refs.childForm.clearValidate(key);
            }, 0);
        });
        this.typeForm.parentId = data.primaryKey;
        this.showChild = true;
        switch (data.category) {
          case '1':
            //分类
            this.chargeItemCategory = [
              { key: '1', value: '分类' },
              { key: '2', value: '事项' },
            ];
            break;
          case '2':
            //事项
            this.chargeItemCategory = [{ key: '3', value: '费项' }];
            break;
          default:
            break;
        }
        this.randomString();
      },
      async update(data) {
        this.showChild = true;
        Object.keys(this.typeForm).forEach(key => {
          (this.typeForm[key] = null),
            setTimeout(() => {
              this.$refs.childForm.clearValidate(key);
            }, 0);
        });
        this.chargeItemCategory = this.constantList.chargeItemCategory;
        let res = await businessDetail({
          primaryKey: data.primaryKey,
        });
        this.typeForm = Object.assign(this.typeForm, res);
        this.typeForm.billTypeList = res.billType ? res.billType.split(',') : [];
        this.typeForm.relationAssetTypeList = res.relationAssetType ? res.relationAssetType.split(',') : [];
      },
      cancel() {
        this.showChild = false;
        Object.keys(this.typeForm).forEach(key => (this.typeForm[key] = null));
      },
    },
  };
</script>
<style lang="scss" scoped>
  .management-tree {
    width: 100%;
    padding: 20px;
    .tree-form {
      display: flex;
      justify-content: flex-start;
      .tree-box {
        width: 40%;
        height: calc(100vh - 150px);
        overflow-y: auto;
        overflow-x: hidden;
        .el-tree {
          position: relative;
          cursor: default;
          background: #fff;
          color: #606266;
          width: 100% !important;
        }
      }
      .form-box {
        width: 60%;
        display: flex;
        justify-content: center;
        .form-box-item {
          width: 70%;
          display: flex;
          justify-content: flex-start;
          flex-direction: column;
          .dialog-footer {
            display: flex;
            justify-content: flex-end;
          }
        }
      }
    }
    .custom-tree-node {
      // flex: 1;
      display: block;
      // align-items: center;
      // justify-content: space-between;
      font-size: 14px;
      padding-right: 8px;
    }
    ::v-deep .el-dialog {
      height: 90%;
    }
    ::v-deep .el-dialog__body{
      height: 85%;
      overflow-y: auto;
    }
  }
</style>
